package com.kgc.onlineLife.controller;

import com.kgc.onlineLife.bean.Product;
import com.kgc.onlineLife.service.CategoryService;
import com.kgc.onlineLife.service.PageService;
import com.kgc.onlineLife.service.ProductService;
import com.kgc.onlineLife.service.ProductsService;
import com.kgc.onlineLife.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * Created On : 2022/4/18.
 * <p>
 * Author     : 98730
 * <p>
 * Description: 商品Controller
 */
@Controller
public class ProductController {

    @Autowired
    ProductsService productsService;

    @Autowired
    private ProductService productService;

    @Autowired
    private PageService pageService;

    @Autowired
    private CategoryService categoryService;

    @RequestMapping("/toAddCart/{id}")
    public String toAddCart(@PathVariable("id") int id, HttpSession session, Map<String,Object> map){
        map.put("product",productsService.selectProductById(id));

        return "Fore/forepage/index2";
    }

    /**
     * @author : nainai
     * @date   : 2022/4/17
     * @param  : [java.util.Map<java.lang.String,java.lang.Object>, java.lang.Integer]
     * @return : java.lang.String
     * @description : 显示所有商品
     */
    @RequestMapping("/products/{pageNo}")
    public String products(Map<String, Object> map, @PathVariable("pageNo") Integer pageNo){
        System.out.println("进入请求/products/");
        // 调用业务接口，获取分页
        Page page = pageService.queryPage("product");
        page.setPageSize(6);
        page.setPageNo(pageNo);
        map.put("page", page);

        // 标识是否为搜索的内容分页
        map.put("searchPage", false);

        // 调用业务接口，获取所有商品信息
        map.put("products", productService.queryProducts(page));

        return "/Admin/goods_list";
    }

    /**
     * @author : nainai
     * @date   : 2022/4/17
     * @param  : [java.util.Map<java.lang.String,java.lang.Object>, java.lang.String]
     * @return : java.lang.String
     * @description : 商品搜索
     */
    @RequestMapping(value = "/searchProduct", method = RequestMethod.GET, params = "name")
    public String searchProduct(Map<String, Object> map, String name){
        // 为空时查全部
        if (name == null || name == "") {
            return "redirect:/products/1";
        }
        // 调用业务接口，查询分页
        Page page = pageService.queryPageByName(name, "product");
        map.put("page", page);

        // 搜索时不显示分页
        map.put("searchPageFlag", true);

        map.put("products", productService.queryProductsByName(name));

        return "/Admin/goods_list";
    }

    /**
     * @author : nainai
     * @date   : 2022/4/17
     * @param  : [java.util.Map<java.lang.String,java.lang.Object>, java.lang.Integer]
     * @return : java.lang.String
     * @description : 删除商品
     */
    @RequestMapping(value = "/deleteProduct/{id}", method = RequestMethod.DELETE)
    public String deleteProduct(@PathVariable("id") Integer id){
        // 调用业务接口，删除商品
        if(productService.removeProductById(id)){
            System.out.println("删除成功！");
        } else {
            System.out.println("删除失败！");
        }

        return "redirect:/products/1";
    }

    /**
     * @author : nainai
     * @date   : 2022/4/17
     * @param  : [java.util.Map<java.lang.String,java.lang.Object>, java.lang.Integer]
     * @return : java.lang.String
     * @description : 修改售卖状态
     */
    @RequestMapping(value = "/modOnline/{id}", method = RequestMethod.PUT)
    public String modOnline(Map<String, Object> map, @PathVariable("id") Integer id){
        // 调用业务接口，修改商品上线状态
        if (productService.modOnline(id)){
            System.out.println("修改成功！");
        } else {
            System.out.println("修改失败！");
        }

        return "redirect:/products/1";
    }

    /**
     * @author : nainai
     * @date   : 2022/4/17
     * @param  : [com.kgc.onlineLife.bean.Product, javax.servlet.http.HttpSession, org.springframework.web.multipart.MultipartFile]
     * @return : java.lang.String
     * @description : 跳转至添加商品页面
     */
    @RequestMapping("/toAddProduct")
    public String toAddProduct(Map<String, Object> map) {
        // 获取所有商品分类
        map.put("categories", categoryService.queryCategoriesNoPage());

        return "/Admin/goods_add";
    }

    /**
     * @author : nainai
     * @date   : 2022/4/17
     * @param  : [com.kgc.onlineLife.bean.Product, javax.servlet.http.HttpSession, org.springframework.web.multipart.MultipartFile]
     * @return : java.lang.String
     * @description : 添加商品
     */
    @RequestMapping("/addProduct")
    public String addProduct(Product product, HttpSession session, MultipartFile imagePro) throws IOException {
        // 调用业务接口，添加商品
        if (imagePro != null) {
            String imageName = UUID.randomUUID().toString().substring(0, 8)+".jpg";
            File file = new File(session.getServletContext().getRealPath("Fore/images/product"),imageName);

            if(!file.exists()){
                file.mkdirs();
            }
            imagePro.transferTo(file);

            product.setImageUrl("images/product/" + imageName);
        }
        productService.addProduct(product);

        return "redirect:/products/1";
    }

    /**
     * @author : nainai
     * @date   : 2022/4/17
     * @param  : [com.kgc.onlineLife.bean.Product, javax.servlet.http.HttpSession, org.springframework.web.multipart.MultipartFile]
     * @return : java.lang.String
     * @description : 跳转至修改商品页面
     */
    @RequestMapping("/toModProduct/{id}")
    public String toModProduct(Map<String, Object> map, @PathVariable("id") Integer id) {
        // 获取所有商品分类
        map.put("categories", categoryService.queryCategoriesNoPage());

        map.put("product", productService.queryProductById(id));

        return "/Admin/goods_edit";
    }

    @RequestMapping("/modProduct/{id}")
    public String toModProduct(@PathVariable("id") Integer id, Product product, HttpSession session, MultipartFile imagePro) throws IOException {
        // 根据id修改商品信息
        if (!imagePro.isEmpty()) {
            // 上传图片不为空
            String imageName = UUID.randomUUID().toString().substring(0, 8) + ".jpg";
            String realPath = session.getServletContext().getRealPath("Fore/images/product");
            File file = new File(realPath, imageName);
            if(!file.exists()){
                file.mkdirs();
            }

            imagePro.transferTo(file);

            product.setImageUrl("images/product/" + imageName);
            productService.modProductById(product);
        } else {
            // 上传图片为空
            productService.modProductById(product);
        }

        return "redirect:/products/1";
    }
}
